package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.sikadwa.lib_permission.OnPermissionCallback
import com.sikadwa.lib_permission.Permission
import com.sikadwa.lib_permission.XXPermissions
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageFaceBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.CameraFaceActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.gilde.ImageUtil
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/23 10:31
 * @Annotation：人脸识别
 */
class FacePage: ProFragment() {

    lateinit var binding: PageFaceBinding
    //本地预览地址
    var faceImgPath = ""
    //拍摄的头像地址
    var faceImgUrl = ""

    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageFaceBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        showFaceBeforeView()
    }

    override fun initListener() {
        binding.imgView.setOnClickListener {
            if (faceImgPath.isEmpty()){
                binding.btnSubmitAndStart.callOnClick()
            }
        }
        //开始 、 提交
        binding.btnSubmitAndStart.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                    addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                    faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
                } else {
                    XXPermissions.with(requireContext())
                        // 申请多个权限
                        .permission(Permission.CAMERA)
                        .request(object: OnPermissionCallback {
                            override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,Permission.CAMERA)
                                addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                                faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
                            }
                            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,Permission.CAMERA)
                                XXPermissions.startPermissionActivity(context!!,permissions)
                            }
                        })
                }
                return@setOnClickListener
            }
            //提交
            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.OCR_INFO)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            addEvent(EventType.CLICK.CLICK_STEP_FACE_CONFIRM_SUBMIT,"")
            val act = context as ProcessActivity
            act.submitAction(params)
        }

        //删除
        binding.removeLayout.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_FACE_REMOVE_PHOTO,faceImgUrl)
            if (faceImgPath.isNotEmpty()){
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
                faceImgPath = ""
            }
            faceImgUrl = ""
            showFaceBeforeView()
        }
    }

    override fun initData() {

    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            FragmentActivity.RESULT_OK -> {
                faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                HHLog.e(">>>>>>>>>Face imgLocalPath：$faceImgPath")
                showFaceAfterView()
                uploadImageAction(faceImgPath)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFaceBeforeView(){
        binding.imgView.setImageResource(R.mipmap.img_face_default_avater)
        binding.removeLayout.visibility = View.INVISIBLE
        binding.btnSubmitAndStart.text = getString(R.string.process_face_start)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFaceAfterView(){
        ImageUtil.instance!!.loadImageUrl(context,binding.imgView,faceImgPath)
        binding.removeLayout.visibility = View.VISIBLE
        binding.btnSubmitAndStart.text = getString(R.string.process_face_submit)
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl,File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                faceImgUrl = data.optJSONObject("obj")!!.optString("url")
                addEvent(EventType.CLICK.CLICK_STEP_FACE_USE_PHOTO, faceImgUrl)
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_STEP_FACE_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_STEP_FACE_END,"")
    }
}